/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-03-07     Hao       the first version
 */
#include <hardware/adc_operate.h>

#define ADC_DEV_NAME        "adc1"      /* ADC 设备名称 */
#define REFER_VOLTAGE       330         /* 参考电压 3.3V,数据精度乘以100保留2位小数*/
#define CONVERT_BITS        (1 << 12)   /* 转换位数为12位 */

static rt_adc_device_t adc_dev = RT_NULL;

int adc_operate_init(void)
{
    /* 查找设备 */
    adc_dev = (rt_adc_device_t) rt_device_find(ADC_DEV_NAME);

    RT_ASSERT(adc_dev != RT_NULL);

    return 0;
}
INIT_APP_EXPORT(adc_operate_init);

// 这里硬件上，A相就是通道0，B相就是通道1，C相就是通道2
float adc_getChVoltage(uint8_t ch)
{
    rt_uint32_t value, vol;

    /* 使能设备 */
    rt_adc_enable(adc_dev, ch);

    /* 读取采样值 */
    value = rt_adc_read(adc_dev, ch);
    /* 转换为对应电压值 */
    vol = value * REFER_VOLTAGE / CONVERT_BITS;

    /* 关闭通道 */
    rt_adc_disable(adc_dev, ch);

    return ((float) vol / 100);
}

#if 0

void adc_voltage_test()
{
    for(uint8_t i = 0; i < 10; i++)
    {
        for(uint8_t ch = 0; ch < 3; ch++)
        {
            int vol = (int)(adc_getChVoltage(ch) * 1000);

            rt_kprintf("%d voltage = %d.%d \n", ch, vol/1000, vol%1000);
        }
        rt_kprintf("--------------------\n");
        rt_thread_mdelay(1000);
    }
}
MSH_CMD_EXPORT(adc_voltage_test, adc voltage test);

#endif
